#include "comboboxdelegate.h"

#include "../propertyeditor.h"

#include <QtGui/QComboBox>

using namespace gui;

ComboBoxDelegate::ComboBoxDelegate(PropertyEditor* parent) :
    QStyledItemDelegate(parent),
    m_parent(parent)
{

}

ComboBoxDelegate::~ComboBoxDelegate()
{

}

QWidget* ComboBoxDelegate::createEditor(QWidget* parent,
    const QStyleOptionViewItem& option,
    const QModelIndex& index) const
{
    QComboBox* editor = new QComboBox(parent);
    editor->setFrame(false);
    editor->installEventFilter(const_cast<ComboBoxDelegate* >(this));

    return editor;
}

void ComboBoxDelegate::setEditorData(QWidget* editor,
    const QModelIndex& index) const
{
    QComboBox* _editor = qobject_cast<QComboBox* >(editor);

    const QString property = index.data(Qt::UserRole).toString();
    const QString value = index.data().toString();
    const QVariantList options = m_parent->m_object->optionList(property);

    int _index = -1;

    for (int i = 0; i < options.size(); ++i)
    {
        if (value == options[i].toString())
        {
            _index = i;
        }
        _editor->addItem(options[i].toString());
    }

    _editor->setCurrentIndex(_index);
}

void ComboBoxDelegate::setModelData(QWidget* editor,
    QAbstractItemModel* model,
    const QModelIndex& index) const
{
    QComboBox* _editor = qobject_cast<QComboBox* >(editor);

    model->setData(index, _editor->currentText());
}

void ComboBoxDelegate::updateEditorGeometry(QWidget* editor,
    const QStyleOptionViewItem& option,
    const QModelIndex& index) const
{
    editor->setGeometry(option.rect);
}
